/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.knowledge.plans;

import com.environment.Aim;
import com.environment.Percept;
import com.environment.Tile;
import com.knowledge.facts.Condition;
import com.knowledge.facts.Fact;
import com.knowledge.facts.FactRepository;
import com.knowledge.facts.FoodFact;
import com.knowledge.facts.FriendlyAntFact;
import com.knowledge.facts.paths.GotoFoodPathFact;
import com.utils.InvalidException;
import com.utils.WeightedDistance;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 *
 * @author keithballantyne
 */
@SuppressWarnings("unchecked")
public class GotoFoodPlan extends Plan {


    public GotoFoodPlan() {
        preconditions.add(new Condition(Condition.Op.ASSERT,FoodFact.class));
        
        postconditions.add(new Condition(Condition.Op.CLEAR,FoodFact.class));
        postconditions.add(new Condition(Condition.Op.ASSERT,FriendlyAntFact.class));
    }


    @Override
    public void calculateUtility() {
        Set<Fact> foods = FactRepository.getInstance().getInstances(FoodFact.class);
        List<FriendlyAntFact> ants = new ArrayList(FactRepository.getInstance().getFriendlyAnts());
        
        if (foods.isEmpty()) return;
        for (Fact food: foods) {
            try {
                Collections.sort(ants,new WeightedDistance(food.getLocation()));
                FriendlyAntFact myAnt = ants.iterator().next();
                GotoFoodPathFact path = (GotoFoodPathFact) myAnt.getReference(GotoFoodPathFact.class);
                
                // if closest ant has a path to the food, update utility of existing food path.
                if (path != null && food.getLocation().equals(path.getLocation())) {
                    path.setUtility(6*Percept.getInstance().getViewRadius2() - path.getRemainingSteps()*path.getRemainingSteps());
                // otherwise create a path and associate it with the ant.
                } else {
                    List<Aim> directions = Percept.getInstance().getDirections(myAnt.getLocation(), food.getLocation());

                    path = new GotoFoodPathFact(myAnt.getLocation(),food.getLocation(),directions);
                    path.setUtility(6*Percept.getInstance().getViewRadius2() - path.getRemainingSteps()*path.getRemainingSteps());
                    FactRepository.getInstance().addInstance(path);
                    myAnt.setReference(path);
                }
                               
//                movement.add(new Order(path.getSource(),path.getNextAim()));
            } catch (InvalidException ex) {
//                Logger.getLogger(GotoFoodPlan.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public Set<Condition> getMissingPreconditions() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
}
